import csv
import json
import markdown_to_json


def contains_list_of_lists(outer_list):
    for element in outer_list:
        if isinstance(element, list):
            return True
    return False

with open(r'C:\Users\Dapan1\Desktop\中医病证脑图.md', 'r', encoding='utf8') as f:
    value = f.read()

dictified = markdown_to_json.dictify(value)
print(dictified)
jsonified = markdown_to_json.jsonify(value)
json_ = json.loads(jsonified)
print(json.dumps(json_['中医病证思维导图'], ensure_ascii=False))
print(json_['中医病证思维导图'])
w_data = []
data = json_['中医病证思维导图']
for key, value in data.items():
    # print(key, value)
    for key2, value2 in value.items():
        # print(key2, value2)
        bm = key2.split('、')[-1]
        gj_ = value2['歌诀']
        if isinstance(gj_, dict):
            gj = ""
            for k, v in gj_.items():
                v_ = '<br>'.join(v)
                gj += f"<h4>{k}</h4>{v}"
        elif isinstance(gj_, str):
            gj = gj_
        else:
            gj = '\n'.join(gj_)

        zx_str = ""
        zx_ = value2['证型']
        # if type(zx_) not in [dict, list]:

        if isinstance(zx_, dict):
            for key3, value3 in zx_ .items():
                print(key3)
                zx_str += f"<h4>{key3}</h4>{'<br>'.join(value3)}"
        else:
            # print(type(zx_), zx_)
            if not contains_list_of_lists(zx_):
                zx_str += '<br>'.join(zx_)
                print(zx_str)
            else:
                print(zx_)
                for ii in zx_:
                    if isinstance(ii, list):
                        print(ii)
                        zx_str += "<br>".join(ii) + '<br>'
                    else:
                        zx_str += (ii + '<br>')
                print(zx_str)
                # zx_str += f"{}"
        w_data.append({"bm": bm.strip(),
                       "gj": gj.strip(),
                       "zx": zx_str.strip()})
        # if not contains_list_of_lists(value2['证型']br):
        #     print(value2['证型'])
        #     for key3, value3 in value2['证型'].items():
        #         print(key3)
        # w_data.append({"bm": bm,
        #                "gj": gj,
        #                "zx": zx_str})

# 打开一个CSV文件以写入数据
with open('output.csv', 'w', newline='', encoding='utf8') as csvfile:
    # 创建一个CSV writer对象
    writer = csv.writer(csvfile)

    # # 写入CSV文件的列名（可选，但推荐）
    # writer.writerow(['病名', '歌诀', '证型'])

    # 遍历JSON数据并写入CSV文件
    for row in w_data:
        writer.writerow([row['bm'], row['gj'], row['zx']])
